package com.bulunsh.wensen.service;

import com.bulunsh.wensen.model.AuthenticationRequest;
import com.bulunsh.wensen.model.UserDto;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Service
public class AuthenticationServiceImpl implements  AuthenticationService {
    @Override
    public UserDto Authentication(AuthenticationRequest authenticationRequest) {

        if (authenticationRequest == null
        || StringUtils.isEmpty(authenticationRequest.getUsername())
        || StringUtils.isEmpty(authenticationRequest.getPassword())) {
            throw new RuntimeException("账号或者密码为null");
        }
        //模拟查数据库
        UserDto userDto = getUserDto(authenticationRequest.getUsername());
        if (userDto == null) {
            throw new RuntimeException("没有此用户");
        }
        if (!authenticationRequest.getPassword().equals(userDto.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        return userDto;
    }

    public UserDto getUserDto(String username){
        return userDtoMap.get(username);
    }

    private Map<String,UserDto> userDtoMap = new HashMap<>();
    {
        Set<String> authorities1 = new HashSet<>();
        authorities1.add("r1");//人为和r1 对应
        Set<String> authorities2 = new HashSet<>();
        authorities2.add("r2");
        userDtoMap.put("zhangsan",new UserDto("1","zhangsan","12345",authorities1));
        userDtoMap.put("lisi",new UserDto("1","lisi","123",authorities2));
    }
}
